<template>
  <div class="codemirrorJs">
    <textarea ref="mycode" class="textarea" v-model="textarea"></textarea>
  </div>
</template>

<script>
import 'codemirror/theme/ambiance.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/addon/hint/show-hint.css'

import CodeMirror from 'codemirror'
import 'codemirror/addon/edit/matchbrackets'
import 'codemirror/addon/selection/active-line'
import 'codemirror/mode/javascript/javascript'
import 'codemirror/addon/hint/show-hint'
import 'codemirror/keymap/sublime.js'
import 'codemirror/addon/selection/active-line.js'
import 'codemirror/addon/edit/matchbrackets.js'
import 'codemirror/addon/display/autorefresh.js'

export default {
  name: 'codemirrorJs',
  props: {
    value: '',
    default: String
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      textarea: '',
      code: ''
    }
  },
  watch: {
    value: {
      handler(val) {
        this.textarea = val
      },
      immediate: true
    }
  },
  mounted() {
    this.editorInit()
  },
  methods: {
    editorInit() {
      const editorText = CodeMirror.fromTextArea(this.$refs.mycode, {
        mode: { name: 'javascript', globalVars: true },
        lint: true,
        tabSize: 2,
        smartIndent: true, // 是否智能缩进
        styleActiveLine: false, // 当前行高亮
        lineNumbers: true, // 显示行号
        gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter', 'CodeMirror-lint-markers'],
        lineWrapping: false, // 自动换行
        matchBrackets: true, // 括号匹配显示
        autoCloseBrackets: true, // 输入和退格时成对
        readOnly: false, // 只读
        foldGutter: true,
        extraKeys: { Ctrl: 'autocomplete' }, // 自定义快捷键
        // lineWrapping

        hintOptions: {
          // 自定义提示选项
          tables: {
            users: ['name', 'score', 'birthDate'],
            countries: ['name', 'population', 'size']
          }
        }
      })
      // 可选,挂载一下监听事项
      editorText.on('change', cm => {
        this.code = cm.getValue() // 这里要用多一个载体去获取值,不然会重复赋值卡顿
        this.$emit('change', this.code)
      })
    }
    // refresh() {
    //   this.$nextTick(() => {
    //     this.editorText.refresh()
    //   })
    // },
    // setValue() {
    //   this.cminstance.setValue(this.textarea)
    //   this.refresh()
    // }
  }
}
</script>

<style lang="scss" scoped>
.codemirrorJs {
  .textarea {
    height: 200px;
  }
}
</style>